<template>
  <div class="app-container">
    <el-card class="box-card" style="min-height: 800px">
      <div slot="header" class="clearfix">

        <div class="media-display">
          <el-link :underline="false" style="font-size: 20px">管理员列表</el-link>
          <el-divider direction="vertical"></el-divider>
          <el-button type="primary" size="small" plain @click="addAdminFormDialog = true">添加管理员</el-button>
        </div>
        <div style="margin-left: auto">

          <el-form :inline="true" :model="condition"  class="demo-form-inline">
            <el-form-item label="账号">
              <el-input v-model="condition.userId" placeholder="用户id"></el-input>
            </el-form-item>
            <el-form-item label="用户名">
              <el-input v-model="condition.username" placeholder="用户名"></el-input>
            </el-form-item>
            <el-form-item label="状态">
              <el-select v-model="condition.state" placeholder="请选择状态">
                <el-option
                  v-for="item in options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="success" plain @click="init">查询</el-button>
              <el-button type="primary" plain @click="viewAll">全部用户</el-button>
            </el-form-item>
          </el-form>

        </div>
      </div>
      <div class="text">
        <el-table
          highlight-current-row
          :data="page.list"
          style="width: 100%">
          <!--展开行-->
          <el-table-column type="expand">
            <template slot-scope="props">
              <el-form label-position="left" inline class="demo-table-expand">
                <el-form-item label="用户 ID">
                  <span>{{ props.row.userId }}</span>
                </el-form-item>
                <el-form-item label="角色">
                  <el-popover trigger="hover"
                              placement="top"
                              style="display: inline-block"
                              v-for="(roleId,index) in props.row.roleId.split(',')"
                              :key="index">
                    <span v-if="roleId === '1'">超级管理员，拥有所有权限</span>
                    <span v-else-if="roleId === '2'">管理员，拥有部分权限</span>
                    <span v-else>普通用户，拥有一般权限</span>
                    <div slot="reference" class="name-wrapper" >
                      <el-tag style="cursor: pointer;margin-right: 5px"
                              :type="roleId === '1' ? 'warning': (roleId === '2' ? 'primary' : 'success')">
                        <span>{{ roleId | roleIdToStr }}</span>
                      </el-tag>
                    </div>
                  </el-popover>
                </el-form-item>
                <el-form-item label="用户账号">
                  <span>{{ props.row.username }}</span>
                </el-form-item>
                <el-form-item label="电话">
                  <span v-if="props.row.phone===undefined">暂无</span>
                  <span v-else>{{ props.row.phone }}</span>
                </el-form-item>
                <el-form-item label="密码">
                  <span>{{ props.row.password }}</span>
                  <el-popconfirm
                    confirm-but ton-text='好的'
                    cancel-button-text='不用了'
                    icon="el-icon-info"
                    icon-color="red"
                    title="是否重置密码？" @onConfirm="resetPassword(props.$index,props.row.userId)">
                    <el-button slot="reference" type="primary" size="mini" plain style="margin-left: 5px">重置密码</el-button>
                  </el-popconfirm>
                </el-form-item>
                <el-form-item label="邮箱">
                  <span v-if="props.row.email===undefined">暂无</span>
                  <span v-else>{{ props.row.email }}</span>
                </el-form-item>
              </el-form>
            </template>
          </el-table-column>
          <el-table-column
            type="index"
            :index="(this.page.currentPage-1)*this.page.pageSize + 1"
            width="50">
          </el-table-column>
          <el-table-column
            label="用户 ID"
            prop="userId">
          </el-table-column>
          <el-table-column
            label="用户账号"
            prop="username">
          </el-table-column>
          <el-table-column
            label="姓名"
            prop="name">
          </el-table-column>
          <el-table-column
            label="角色"
            prop="roleId">
            <template slot-scope="scope">
              <el-popover trigger="hover"
                          placement="top"
                          style="display: inline-block"
                          v-for="(roleId,index) in scope.row.roleId.split(',')"
                          :key="index">
                <span v-if="roleId === '1'">超级管理员，拥有所有权限</span>
                <span v-else-if="roleId === '2'">这是管理员，拥有部分权限</span>
                <span v-else>普通用户，拥有一般权限</span>
                <div slot="reference" class="name-wrapper" >
                  <el-tag style="cursor: pointer;margin-right: 5px"
                          :type="roleId === '1' ? 'warning': (roleId === '2' ? 'primary' : 'success')">
                    <span>{{ roleId | roleIdToStr }}</span>
                  </el-tag>
                </div>
              </el-popover>

              <el-button type="primary" @click="getUserRole(scope.$index,scope.row.userId)" plain size="mini" icon="el-icon-edit" circle></el-button>
            </template>
          </el-table-column>
          <el-table-column
            width="200"
            align="center"
            label="状态(锁定/正常)">
            <template slot-scope="scope" >
              <el-popconfirm
                :disabled="scope.row.roleId.split(',').includes('super')"
                confirm-but ton-text='好的'
                cancel-button-text='不用了'
                icon="el-icon-info"
                icon-color="red"
                title="是否更改用户状态？" @onConfirm="modifyAdminState(scope.$index,scope.row.userId,scope.row.state)">
                <el-switch
                  slot="reference"
                  disabled
                  v-model="scope.row.state"
                  :active-value="1"
                  :inactive-value="0">
                </el-switch>
              </el-popconfirm>
            </template>
          </el-table-column>

          <el-table-column
            label="操作">
            <template slot-scope="scope">
              <el-button size="small" type="primary" @click="getInfo(scope.$index,scope.row.userId)">修改</el-button>
              <el-button slot="reference" size="small" type="danger"
                         :disabled="scope.row.roleId.split(',').includes('super')"
                         @click="open()">删除</el-button>
            </template>

          </el-table-column>
        </el-table>

        <!--分页-->
        <el-pagination style="text-align: center"
                       @current-change="handleCurrentChange"
                       :current-page="this.page.currentPage"
                       :page-size="this.page.pageSize"
                       layout="total, prev, pager, next, jumper"
                       :total="this.page.total">
        </el-pagination>
      </div>
    </el-card>

    <el-dialog
      width="50%"
      title="添加管理员"
      :visible.sync="addAdminFormDialog"
      :before-close="handleClose">
      <div>
        <el-form :model="addAdminForm" :rules="addAdminFormRules" ref="modifyAllInfoForm" style="width: 90%;margin: 0 auto;" label-width="100px">
          <el-form-item label="用户id">
            <el-input value="userId自动生成" disabled prefix-icon="el-icon-user-solid"></el-input>
          </el-form-item>
          <el-form-item label="账号" prop="username">
            <el-input v-model="addAdminForm.username" prefix-icon="el-icon-user-solid"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="addAdminForm.password" prefix-icon="el-icon-user-solid"></el-input>
          </el-form-item>
          <el-form-item label="状态" prop="state">
            <el-switch
              v-model="addAdminForm.state"
              :active-value="1"
              :inactive-value="0">
            </el-switch>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addAdminFormDialog  = false">取 消</el-button>
        <el-popconfirm
          style="margin-left: 10px"
          confirm-but ton-text='好的'
          cancel-button-text='不用了'
          icon="el-icon-info"
          icon-color="red"
          title="是否添加？" @onConfirm="addAdmin">
          <el-button type="primary" slot="reference">确 定</el-button>
        </el-popconfirm>
      </div>
    </el-dialog>

    <el-dialog
      width="50%"
      title="修改信息"
      :visible.sync="modifyAllInfoDialog"
      :before-close="handleClose">
      <div v-loading="dialogLoading" >
        <el-form :model="modifyAllInfoForm" :rules="rules" ref="modifyAllInfoForm" style="width: 90%;margin: 0 auto;" label-width="100px">
          <el-form-item label="用户id" prop="userId">
            <el-input v-model="modifyAllInfoForm.userId" disabled prefix-icon="el-icon-user-solid"></el-input>
          </el-form-item>
          <el-form-item label="账号" prop="username">
            <el-input v-model="modifyAllInfoForm.username" disabled prefix-icon="el-icon-user-solid"></el-input>
          </el-form-item>
<!--          <el-form-item label="密码" prop="password">
            <el-input v-model="modifyAllInfoForm.password" prefix-icon="el-icon-user-solid"></el-input>
          </el-form-item>-->
          <el-form-item label="状态" prop="state">
            <el-switch
              v-model="modifyAllInfoForm.state"
              :active-value="1"
              :inactive-value="0">
            </el-switch>
          </el-form-item>
          <el-form-item label="姓名" prop="name">
            <el-input v-model="modifyAllInfoForm.name" prefix-icon="el-icon-user-solid"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="modifyAllInfoForm.email" prefix-icon="el-icon-platform-eleme"></el-input>
          </el-form-item>
          <el-form-item label="手机" prop="phone">
            <el-input v-model="modifyAllInfoForm.phone" prefix-icon="el-icon-phone-outline"></el-input>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="modifyAllInfoDialog = false">取 消</el-button>
        <el-popconfirm
          style="margin-left: 10px"
          confirm-but ton-text='好的'
          cancel-button-text='不用了'
          icon="el-icon-info"
          icon-color="red"
          title="是否修改用户信息？" @onConfirm="submitForm('modifyAllInfoForm')">
          <el-button type="primary" slot="reference">确 定</el-button>
        </el-popconfirm>
      </div>
    </el-dialog>

    <el-dialog
      width="30%"
      title="修改角色"
      :visible.sync="modifyRoleFormDialog"
      :before-close="handleClose">
      <div>
        <el-form :model="modifyRoleForm" ref="modifyRoleFormDialog" style="width: 90%;margin: 0 auto;" label-width="100px">
          <el-form-item label="用户id" prop="userId">
            <el-input v-model="modifyRoleForm.userId" disabled prefix-icon="el-icon-user-solid"></el-input>
          </el-form-item>
          <el-form-item label="角色" prop="roleName">
            <template>
              <el-checkbox-group v-model="roleIdList" @change="handleChecked">
                <el-checkbox label="1" border size="medium">super</el-checkbox>
                <el-checkbox label="2" border size="medium">admin</el-checkbox>
                <el-checkbox label="3" border size="medium">user</el-checkbox>
              </el-checkbox-group>
            </template>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="modifyRoleFormDialog = false">取 消</el-button>
        <el-popconfirm
          style="margin-left: 10px"
          confirm-but ton-text='好的'
          cancel-button-text='不用了'
          icon="el-icon-info"
          icon-color="red"
          title="是否修改用户信息？" @onConfirm="modifyAdminRole()">
          <el-button type="primary" slot="reference">确 定</el-button>
        </el-popconfirm>
      </div>
    </el-dialog>

  </div>
</template>


<script>
  import { getAdminByUsernameReq, resetPasswordReq, addAdminReq, getAdminListReq, modifyAdminStateReq, getAdminInfoReq, modifyAdminInfoReq, modifyAdminRoleReq } from '@/api/adminUser'

  export default {
    name: "UserRole",
    data(){
      return{
        options: [{
          value: '0',
          label: '封禁'
        }, {
          value: '1',
          label: '正常'
        }],

        addAdminFormDialog: false,
        addAdminForm: {
          username: "",
          password: "",
          state: 1,
        },

        dialogLoading: true,
        modifyAllInfoDialog: false,
        modifyAllInfoForm:{
        },
        roleIdList: [],

        modifyRoleFormDialog: false,
        modifyRoleForm: {
          userId: "",
          roleIdList: [],
        },

        condition: {
          state: '',// 账号状态
          userId : '',// 用户id
          username : '',// 用户名
          currentPage: 1,
        },
        addAdminFormRules: {
          username: [
            { required: true, message: '请选输入username', trigger: 'blur' },
            { min: 3, message: '长度不小于 3 个字符 ', trigger: 'blur' },
            { validator: (rule, value, callback) => {
                if (value) {
                  if (/\s/g.test(value)) {
                    callback(new Error("不能有空格"));
                  } else {
                    getAdminByUsernameReq({username: value }).then(res => {
                      console.log(res)
                      if (res.state === true){
                        callback();
                      }else {
                        callback(new Error(res.message));
                      }
                    })
                  }
                }
              }, trigger: 'blur' },
          ],
          password: [
            { required: true, message: '请输入原密码', trigger: 'blur' },
            { min: 3, message: '长度不小于 3 个字符 ', trigger: 'blur' }
          ],
        },
        rules: {//修改密码验证规则
          password: [
            { required: true, message: '请输入原密码', trigger: 'blur' },
            { min: 3, message: '长度不小于 3 个字符 ', trigger: 'blur' }
          ],
          state: [
            { required: true, message: '请输入姓名', trigger: 'blur' },
          ],
          name: [
            { required: true, message: '请输入姓名', trigger: 'blur' },
          ],
          email: [
            { required: true, message: '请输入电子邮箱', trigger: 'blur' },
          ],
          phone: [
            { required: true, message: '请输入电话号码', trigger: 'blur' },
          ],
        },
        roleArr: [{
          describe: '超级管理员',
          value: 1,
          label: 'super'
        }, {
          describe: '普通管理员',
          value: 2,
          label: 'admin'
        }, {
          describe: '用户',
          value: 3,
          label: 'user'
        }],
        globalIndex : 0,

        page : {},
        roles: {//存放要搜索的角色id
          super: true,
          admin: true,
          user: true,
        },
      }
    },
    methods : {
      resetPassword(index, userId){
        resetPasswordReq({userId: userId}).then((response) => {
          console.log(response);
          if (response.state === true){
            this.page.list[index].password = response.data.resetPassword
            this.$message.success({ message: response.message });
          }else {
            this.$message.warning({ message: response.message });
          }
        })
      },
      addAdmin(){
        addAdminReq({addAdminForm: this.addAdminForm}).then((response) => {
          console.log(response);
          if (response.state === true){
            this.init()
            Object.assign(this.$data.addAdminForm, this.$options.data().addAdminForm);
            this.addAdminFormDialog = false
          }else {
            this.$message.warning({ message: response.message });
          }
        })
      },
      handleChecked(value){
        console.log(value)
      },
      open(){
        this.$confirm(`此操作将验证, 是否继续？`, "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
      },
      getUserRole(index,userId){
        this.modifyRoleFormDialog = true
        this.globalIndex = index
        getAdminInfoReq({userId: userId}).then((response) => {
          console.log(response);
          if (response.state === true){
            this.modifyRoleForm.userId = response.data.user.userId
            this.roleIdList = response.data.user.roleId.split(',')
          }else {
            this.$message.warning({ message: response.message });
          }
        })
      },
      getInfo(index,userId){
        console.log(index, userId)
        this.globalIndex = index;
        this.modifyAllInfoDialog = true;//打开修改信息的弹窗
        this.dialogLoading = true;//进入加载

        getAdminInfoReq({userId: userId}).then((response) => {
          console.log(response);
          if (response.state === true){
            this.modifyAllInfoForm = response.data.user;//显示信息
            console.log(this.modifyAllInfoForm)
            this.roleIdList = this.modifyAllInfoForm.roleId.split(',')
            console.log(this.roleIdList)
            this.dialogLoading = false;//取消加载
          }else {
            this.$message.warning({ message: response.message });
          }
        })
      },
      modifyAdminState(index ,userId, state){
        console.log(index, userId)
        state = state ^ 1
        modifyAdminStateReq({userId: userId, state: state}).then(response =>{
          if (response.state === true) {
            this.page.list[index].state = state
            this.$notify.success({title: '成功',message: response.message, duration: 1500});
          }else{
            this.$notify.warning({title: '失败',message: response.message, duration: 1500});
          }
        })
      },
      modifyAdminRole(){
        this.modifyRoleForm.roleIdList = this.roleIdList
        if (this.modifyRoleForm.roleIdList.length === 0) return
        modifyAdminRoleReq({modifyRoleForm: this.modifyRoleForm}).then((response) => {
          console.log(response);
          if (response.state === true){
            this.modifyRoleFormDialog = false
            this.$set(this.page.list[this.globalIndex], 'roleId', this.modifyRoleForm.roleIdList.toString())
          }else {
            this.$message.warning({ message: response.message });
          }
        })
      },
      submitForm(formName) {
        // 如果是修改信息表单要先查询，等待loading状态结束
        if (this.dialogLoading) {console.log("还在加载中");return;}
        this.$refs[formName].validate((valid) => {
          if (valid) {
            console.log(this.modifyAllInfoForm)
            modifyAdminInfoReq({modifyAllInfoForm: this.modifyAllInfoForm}).then((response) => {
              console.log(response);
              if (response.state === true){
                console.log("globalIndex",this.globalIndex)
                this.$set(this.page.list, this.globalIndex, this.modifyAllInfoForm)
                this.modifyAllInfoDialog = false;//关闭dialog
                this.$notify.success({title: '成功',message: response.message, duration: 1500});
              }else {
                this.$message.warning({ message: response.message });
              }
            })
          }
        });
      },
      init(){//初始化数据
        getAdminListReq({condition: this.condition}).then((response) => {
          console.log(response);
          if (response.state === true){
            this.page = response.data.page;
            this.$notify.success({title: '成功',message: response.message, duration: 1500});
          }else {
            this.$message.warning({ message: response.message });
          }
        })
      },
      viewAll(){//查看全部试题
        Object.assign(this.$data.condition, this.$options.data().condition);
        this.init()
      },
      choice(event, roleName){
        if (roleName === "super"){
          this.roles.super = !this.roles.super;
        }else if (roleName === "admin"){
          this.roles.admin = !this.roles.admin;
        }else if (roleName === "user"){
          this.roles.user = !this.roles.user;
        }
        if(event.nodeName === 'SPAN' || event.nodeName === 'I'){
          event = event.parentNode;
        }
        event.blur();
      },

      handleCurrentChange(currentPage){// 处理分页数据
        this.condition.currentPage = currentPage;
        this.init()
      },
      handleClose(done) {
        this.$confirm('确认关闭？').then(_ => {done();}).catch(_ => {});
      },
    },
    filters: {
      roleIdToStr(roleId){
        switch (roleId) {
          case '1':return 'super'
          case '2':return 'admin'
          case '3':return 'user'
        }
      }
    },
    beforeMount (){//初始化数据
      this.init()
    },
    mounted(){
    },
  }
</script>

<style scoped>


  @media (max-width: 1100px){
    .media-display{
      display: none;
    }
  }
  .el-form{
    width: auto;
  }
  *{
    outline: none;
  }
  .clearfix .el-form-item{
    margin-bottom: 0;
  }
  .el-card__header{
    background-color: rgba(0,0,0,.03);
  }
  .el-card__body{
    padding-top: 0;
  }
  .clearfix{
    display: flex;
    align-items: center;
  }
  .text {
    font-size: 14px;
  }
  .clearfix:before,
  .clearfix:after {
    display: table;
    content: "";
  }
  .clearfix:after {
    clear: both
  }

  tr{
    height: 60px;
  }
  .demo-table-expand {
    font-size: 0;
  }
  >>> .demo-table-expand label {
    width: 90px;
    color: #99a9bf;
  }
  .demo-table-expand .el-form-item {
    margin-right: 0;
    margin-bottom: 0;
    width: 50%;
  }
  .el-form--inline .el-form-item__content{
    vertical-align: baseline;
  }
  .el-switch__label{
    color: #909399;
  }

  /*重写switch的disabled时css*/
  >>>.el-switch.is-disabled{
    opacity: 1;
  }
  >>>.el-switch.is-disabled .el-switch__core, .el-switch.is-disabled .el-switch__label{
    cursor: pointer;
  }

  >>>.switch-disabled{
    cursor: no-drop;
  }
</style>
